<!-- 专题创建 -->
<template>
	<div id="tjia" style="width: 70%;">
		<el-form :model="ruleForm" :rules="rules" ref="ruleForm" class="demo-ruleForm">
			<el-form-item label="专题标题" prop="title" :label-width="formLabelWidth">
				<el-input type="text" v-model="ruleForm.title"></el-input>
			</el-form-item>
			<el-form-item label="专题子标题" prop="subtitle" :label-width="formLabelWidth">
				<el-input type="text" v-model="ruleForm.subtitle"></el-input>
			</el-form-item>
			<el-form-item label="专题图片" prop="" :label-width="formLabelWidth">
				<el-upload class="avatar-uploader" :headers="token"
					action="http://192.168.1.54:8080/admin/storage/create" :show-file-list="false"
					:on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
					<img v-if="ruleForm.imageUrl" :src="ruleForm.imageUrl" class="avatar">
					<i v-else class="el-icon-plus avatar-uploader-icon"></i>
				</el-upload>
			</el-form-item>
			<el-form-item label="专题内容" prop="content" :label-width="formLabelWidth">
				<!-- 富文本 -->
				<Editor class="dit" :init="editorInit" v-model="ruleForm.content"></Editor>
			</el-form-item>
			<el-form-item label="商品低价" prop="price" :label-width="formLabelWidth">
				<el-input type="text" v-model="ruleForm.price"></el-input>
			</el-form-item>
			<el-form-item label="阅读量" prop="" :label-width="formLabelWidth">
				<el-input type="text" v-model="ruleForm.readCount"></el-input>
			</el-form-item>
			<el-form-item label="专题商品" prop="" :label-width="formLabelWidth">
				<div class="tjsc">
					<el-button type="primary" size="mini" @click="dialogFormVisible = true">创建商品</el-button>
				</div>
				<el-table border style="width: 700px;" :data="tablelist">
					<el-table-column prop="id" label="商品ID" align="center">
					</el-table-column>
					<el-table-column prop="picUrl" label="图片" align="center">
						<template slot-scope="scope">
							<img :src="scope.row.picUrl" style="width: 50px;height: 50px;" v-if="scope.row.picUrl">
						</template>
					</el-table-column>
					<el-table-column prop="name" label="商品名称" align="center">
					</el-table-column>
					<el-table-column prop="brief" label="商品介绍" align="center">
					</el-table-column>
					<el-table-column prop="" label="操作" align="center">
						<template slot-scope="scope">
							<el-button type="danger" size="mini" @click="del(scope.$index, scope.row)">删除</el-button>
						</template>
					</el-table-column>
				</el-table>
			</el-form-item>
		</el-form>
		<!-- 创建商品弹出框 -->
		<el-dialog title="添加商品" :visible.sync="dialogFormVisible">
			<el-input v-model="number" placeholder="请输入商品编号" :clearable="true" style="width: 150px;"></el-input>
			<el-input v-model="designation" placeholder="请输入商品名称" :clearable="true" style="width: 150px;"></el-input>
			<el-button type="primary" icon="el-icon-search" @click="acquire">查找</el-button>
			<el-table border style="width: 700px;" :data="tableData" @selection-change="checkAll">
				<el-table-column prop="" label="" type="selection" align="center">
				</el-table-column>
				<el-table-column prop="id" label="商品ID" align="center">
				</el-table-column>
				<el-table-column prop="picUrl" label="图片" align="center">
					<template slot-scope="scope">
						<img :src="scope.row.picUrl" style="width: 50px;height: 50px;" v-if="scope.row.picUrl">
					</template>
				</el-table-column>
				<el-table-column prop="name" label="商品介绍" align="center">
				</el-table-column>
			</el-table>
			<!-- 分页 -->
			<el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
				:current-page="currentPage" :page-sizes="[10, 20, 30, 40, 50, 100]" :page-size="10" background
				layout="total, sizes, prev, pager, next, jumper" :total="total"  v-if="this.tableData.length>0">
			</el-pagination>
			<div slot="footer" class="dialog-footer">
				<el-button @click="resetForm('ruleForm')">取 消</el-button>
				<el-button type="primary" @click="petition">确 定</el-button>
			</div>
		</el-dialog>
		<div slot="footer" class="dialog-footer">
			<el-button @click="sikp">取 消</el-button>
			<el-button type="primary" @click="submitForm('ruleForm')">确 定</el-button>
		</div>
	</div>
</template>

<script>
	import Editor from '@tinymce/tinymce-vue'
	import cookie from 'js-cookie'
	import {
		zttian,
		specialGoods
	} from '@/api/http.js'
	export default {
		data() {
			return {
				token: {
					'X-Litemall-Admin-Token': this.$cookie.get("tokens")
				},
				ruleForm: {
					title: '',//专题标题
					subtitle:"",	//专题子标题
					imageUrl: '', //图片
					content:"",	//专题内容
					price:"",	//商品低价
					readCount:"",	//阅读量
					goodsSn:"",	//商品编号
					name:"",	//商品名称
				},
				goods: [], //专题商品
				rules: {
					title: [{
						required: true,
						message: '专题标题不能为空',
						trigger: 'blur'
					}],
					subtitle: [{
						required: true,
						message: '专题子标题不能为空',
						trigger: 'blur'
					}],
					content: [{
						required: true,
						message: '专题内容不能为空',
						trigger: 'blur'
					}],
					price: [{
						required: true,
						message: '专题低价不能为空',
						trigger: 'blur'
					}],
				},
				formLabelWidth: '100px',
				//富文本配置
				editorInit: {
					language: 'zh_CN',
					height: 500,
					width: 700,
					convert_urls: false,
					plugins: [
						'advlist anchor autolink autosave code codesample colorpicker colorpicker contextmenu directionality emoticons fullscreen hr image imagetools importcss insertdatetime link lists media nonbreaking noneditable pagebreak paste preview print save searchreplace spellchecker tabfocus table template textcolor textpattern visualblocks visualchars wordcount'
					],
					toolbar: [
						'searchreplace bold italic underline strikethrough alignleft aligncenter alignright outdent indent  blockquote undo redo removeformat subscript superscript code codesample',
						'hr bullist numlist link image charmap preview anchor pagebreak insertdatetime media table emoticons forecolor backcolor fullscreen'
					],
					images_upload_handler: function(blobInfo, success, failure) {
						const formData = new FormData();
						formData.append('file', blobInfo.blob());
						createStorage(formData)
							.then(res => {
								success(res.data.data.url);
							})
							.catch(() => {
								failure('上传失败，请重新上传');
							});
					}
				},
				number:'',//编号
				designation:"",//名称
				dialogFormVisible : false,
				currentPage: 1,
				total: 0,
				tableData:[],//创建里的表格数据
				// 专题商品表格数据
				tablelist:[],
				checkId:[]
			}
		},
		components: {
			Editor
		},
		created() {
		
		},
		mounted() {

		},
		methods: {
			handleSizeChange(val) { //每页多少条
				let obj = {
					limit: val
				}
				specialGoods().then((res) => {
					console.log(res)
					this.tableData = res.data.data.list
			
				})
			},
			handleCurrentChange(val) { //分页;	
				let obj = {
					page: val,
				}
				specialGoods().then((res) => {
					console.log(res)
					this.tableData = res.data.data.list
				})
			},
			acquire(){//获取数据
				let obj ={
					goodsSn:this.number,
					name:this.designation
				}
				specialGoods().then((res)=>{
					this.tableData=res.data.data.list
					this.total=res.data.data.total
				})
			},
			// 上传头像
			handleAvatarSuccess(res, file) {
				this.ruleForm.imageUrl = file.response.data.url;
			},
			beforeAvatarUpload(file) {
				const isJPG = file.type === 'image/jpeg';
				const isLt2M = file.size / 1024 / 1024 < 2;
				if (!isJPG) {
					this.$message.error('上传头像图片只能是 JPG 格式!');
				}
				if (!isLt2M) {
					this.$message.error('上传头像图片大小不能超过 2MB!');
				}
				return isJPG && isLt2M;
			},
			submitForm(ruleForm) { //提交
				this.$refs[ruleForm].validate((valid) => {
					if (valid) {
						this.add()
					} else {
						console.log('error submit!!');
						return false;
					}
				});
			},
			resetForm(ruleForm) {//取消重置验证
					this.dialogFormVisible=false
			        this.$refs[ruleForm].resetFields();
			 },
			// 删除
			del(index,row){
				console.log(row)
				this.$confirm('删除后将无法恢复,是否继续?', '提示', {
					confirmButtonText: '确定',
					acncelButtonText: '取消',
					type: 'warning'
				}).then(()=>{
						this.tablelist.splice(index,1)				
				})
			},
			
			// 全选
			checkAll(selection) {
				console.log(selection)
				this.checkId=[]
				this.checkId.push.apply(this.checkId,selection)
				let obj = {};
				this.checkId = this.checkId.reduce((cur, next) => {
					// console.log(next)
					obj[next.name] ? "" : obj[next.name] = true && cur.push(next);
					return cur
				}, []) //设置cur默认类型为数组，并且初始值为空的数组
				// console.log(this.checkId,666)
			},
			// 选择后确定
			petition(){
				this.tableData=[]
				// this.tablelist=this.checkId	
				this.tablelist= this.tablelist.concat(this.checkId)
				let obj = {};
				this.tablelist = this.tablelist.reduce((cur, next) => {
					// console.log(next)
					obj[next.name] ? "" : obj[next.name] = true && cur.push(next);
					return cur
				}, []) 
				this.tablelist.forEach(item=>{
					this.goods.push(item.id)
				})
				this.dialogFormVisible = false
			},
			add() { //添加
				let obj = {
					title: this.ruleForm.title,
					subtitle: this.ruleForm.subtitle,
					picUrl: this.ruleForm.imageUrl,
					content: this.ruleForm.content,
					price: this.ruleForm.price,
					readCount: this.ruleForm.readCount,
					goods: this.goods,
					goodsSn: this.ruleForm.goodsSn,
					name: this.ruleForm.name
				}
				zttian(obj).then((res) => {
					console.log(res.data.errmsg)
					if (res.data.errmsg == "成功") {
						this.$notify({
							title: '成功',
							message: '创建成功',
							type: 'success'
						});
						this.$router.replace({
							path: "/promotion/topic"
						})
						window.location.reload()
						this.ruleForm.title=""
						this.ruleForm.subtitle=""
						this.ruleForm.imageUrl=""
						this.ruleForm.content=""
						this.ruleForm.price=""
						this.ruleForm.readCount=""
						this.goods=""
						this.ruleForm.goodsSn=""
						this.ruleForm.name=""
					}else if (res.data.errmsg == "参数不对") {
						this.$notify.error({
							title: '失败',
							message: '参数不对'
						})						
					}
				})
			},
			sikp(){
				this.$router.replace({
					path: "/promotion/topic"				
				})
			},
		}
	}
</script>

<style>
	#tjia .el-form-item {
		font-weight: 700;
		color: #373737;
	}
	
	#tjia .el-form-item .el-input {
		width: 60%;
	}
	
	#tjia .avatar-uploader .el-upload {
		border: 1px dashed #d9d9d9;
		border-radius: 6px;
		cursor: pointer;
		position: relative;
		overflow: hidden;
	}
	
	#tjia .avatar-uploader .el-upload:hover {
		border-color: #409EFF;
	}
	
	#tjia .avatar-uploader-icon {
		font-size: 25px;
		color: #8c939d;
		width: 100px;
		height: 100px;
		line-height: 100px;
		text-align: center;
	}
	
	#tjia .avatar {
		width: 100px;
		height: 100px;
		display: block;
	}
	
	#tjia .tjsc {
		padding-right: 60px;
		font-size: 12px;
		text-align: right;
	}
</style>
